package com.example.testproj.lrucache;

import android.os.Environment;
import android.util.Log;

import com.example.testproj.base.MyApplication;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

import okhttp3.Response;

/**
 * @des:
 * @author: 芮勤
 * @date: 2019/8/8 10:48
 * @see {@link }
 */
public class FilleUtils {
    public static void saveFile(String name, InputStream inputStream){
        File file=new File(MyApplication.getInstance().getExternalCacheDir().getPath()+File.separator+name);
        if (file.exists()){
            file.delete();
        }
        Log.d("FilleUtils", "saveFile: "+file.getAbsolutePath());
        byte[] cacheByte=new byte[1024];
        int len=0;
        BufferedInputStream bufferedInputStream=new BufferedInputStream(inputStream);
        FileOutputStream outputStream=null;
        BufferedOutputStream bufferedOutputStream=null;
        try {
            outputStream=new FileOutputStream(file);
            bufferedOutputStream=new BufferedOutputStream(outputStream);
            while ((len= bufferedInputStream.read(cacheByte))!=-1){
                Log.d("FilleUtils", "saveFile: "+len);
                bufferedOutputStream.write(cacheByte,0,len);
            }
        } catch (Exception e) {
            Log.e("FilleUtils", "保存文件出错",e.getCause() );
            e.printStackTrace();
        }  finally {
            if (inputStream!=null){
                try {
                    bufferedInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (outputStream!=null){
                try {
                    bufferedOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
